package socket

import (
	"bufio"
	"fmt"
	"net"
	"os"
)

func EchoClientLoop() {
	conn, err := net.Dial("tcp", "127.0.0.1:9000")
	if err != nil {
		fmt.Println("err=" + err.Error())
		os.Exit(1)
	}
	fmt.Println("client connected")
	defer conn.Close()

	for i := 0; i < 10; i++ {
		conn.Write([]byte("hello world"))
		//time.Sleep(time.Second)
	}

	var buf [512]byte
	for {
		n, err := conn.Read(buf[:])
		if err != nil {
			fmt.Println("err=" + err.Error())
			return
		}

		fmt.Println(string(buf[:n]))
	}
}

func EchoClientPacket() {
	conn, err := net.Dial("tcp", "localhost:9000")
	if err != nil {
		fmt.Println("err=" + err.Error())
		return
	}

	fmt.Println("client started")
	defer conn.Close()

	for i := 0; i < 10; i++ {
		data, _ := Encode("hello world")
		conn.Write(data)
	}

	bufReader := bufio.NewReader(conn)
	for {
		msg, err := Decode(bufReader)
		if err != nil {
			fmt.Println("err=" + err.Error())
			continue
		}

		if len(msg) > 0 {
			fmt.Println(msg)
		}
	}
}
